import { defineStore } from 'pinia'
import { userApi } from '../api'

interface User {
  id: number
  username: string
  real_name: string
  isadmin: number
  allow_node: number
  age?: number
  gender?: string
}

interface UserState {
  user: User | null
  token: string | null
  isLoggedIn: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: null,
    token: localStorage.getItem('token'), // 只保留token在localStorage中
    isLoggedIn: false
  }),

  getters: {
    isAdmin: (state) => state.user?.isadmin === 1,
    currentAllowNode: (state) => state.user?.allow_node ?? 0
  },

  actions: {
    async login(username: string, password: string) {
      try {
        const response = await userApi.login(username, password)
        
        if (response.success) {
          this.user = response.data
          this.token = response.token || null
          this.isLoggedIn = true
          
          if (response.token) {
            localStorage.setItem('token', response.token)
          }
          
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: '网络错误，请重试' }
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.isLoggedIn = false
      
      localStorage.removeItem('token')
    },

    // 从数据库刷新用户状态
    async refreshUserFromDB() {
      if (!this.user?.id) return { success: false, message: '用户未登录' }
      
      try {
        const response = await userApi.getUserInfo(this.user.id)
        if (response.success) {
          this.user = response.data
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('刷新用户状态失败:', error)
        return { success: false, message: '网络错误' }
      }
    },

    // 恢复登录状态 - 只从token恢复，用户数据从数据库获取
    async restoreUser() {
      const token = localStorage.getItem('token')
      
      if (token) {
        try {
          this.token = token
          // 这里需要根据token获取用户信息，暂时使用token解析用户ID
          const userId = this.extractUserIdFromToken(token)
          if (userId) {
            const response = await userApi.getUserInfo(userId)
            if (response.success) {
              this.user = response.data
              this.isLoggedIn = true
              return { success: true }
            }
          }
        } catch (error) {
          console.error('恢复用户状态失败:', error)
        }
      }
      
      this.logout()
      return { success: false }
    },

    // 从token中提取用户ID（简单解析）
    extractUserIdFromToken(token: string): number | null {
      try {
        // token格式: token_userId_timestamp
        const parts = token.split('_')
        if (parts.length >= 2) {
          return parseInt(parts[1])
        }
      } catch (error) {
        console.error('解析token失败:', error)
      }
      return null
    }
  }
})
